//私聊
import {useLocation, useNavigate} from "react-router-dom";
import Return2Icon from "@src/assets/return2.svg?react"
import "./index.scss"
import {UserInfoType, deleteMessages} from "@src/services/userinfo.ts";
import InputIcon from "@src/components/inputIcon"
import {useEffect, useMemo, useRef, useState} from "react";
import {socketCreate} from "@src/store/socket"
import {formatDate} from "@src/utils/date.ts"
import toast from 'react-hot-toast';
import {usersRelationshipsDataType} from "@src/services/userinfo.ts"
import {newsDataCreate} from "@src/store/newsData.ts";
import {getChatHistory, AddChatHistory, AddChatHistoryList} from "@src/store/chatHistory.ts";


export interface messageType {
    id: number;
    name: string,
    avatar: string,
    time: number,
    content: string,
    type: 0
}

interface messages {
    message: string,
}

function isTimeGapExceeds5Minutes(currentTime: number, previousTime: number): boolean {
    // 计算时间差（单位：分钟）
    const timeDifference = (currentTime - previousTime) / (1000 * 60);
    return timeDifference > 5;
}

export default function PrivateChat() {
    const location = useLocation();
    const navigate = useNavigate();
    const newsData: usersRelationshipsDataType = location.state;
    const {user}: UserInfoType = JSON.parse(localStorage.getItem("UserData") as string);
    const [inputText, setInputText] = useState<string>("");
    const [recordList, setRecordList] = useState<messageType[]>([])
    const recordRef = useRef<HTMLUListElement>(null);
    const {readMessage} = newsDataCreate()
    // 滚动到底部的方法
    const scrollToBottom = () => {
        if (recordRef.current) {
            recordRef.current.scrollTo({
                top: recordRef.current.scrollHeight, // 滚动到元素的底部
                behavior: 'smooth' // 平滑滚动
            });
        }
    };
    const timeGaps = useMemo(() => {
        return recordList.map((item, index) => {
            if (index === 0) {
                // 第一条消息没有上一条消息，直接返回 true
                return true;
            }
            const previousTime = recordList[index - 1].time;
            return isTimeGapExceeds5Minutes(item.time, previousTime);
        });
    }, [recordList]);
    const {socket} = socketCreate();
    useEffect(() => {
        //收到新消息
        socket.on('private_message', (data) => {
            AddChatHistory({
                recipientEmail: data.from.email,
                otherUserEmail: user.email,
                message: JSON.parse(data.message)
            })
            setRecordList((prevState) => [...prevState, JSON.parse(data.message)]);
            setTimeout(scrollToBottom, 100)
        });
        //监听聊天历史
        socket.on('chat_history', (data) => {
            //添加历史到本地
            AddChatHistoryList(data.messages.map((msg: messages) => {
                return {
                    recipientEmail: data.otherUser.email,
                    otherUserEmail: user.email,
                    message: JSON.parse(msg.message)
                }
            }))
            const messageTypeArray: messageType[] = getChatHistory(newsData.friend_email, user.email).map((msg) => msg.message);
            setRecordList(messageTypeArray.reverse())
            setTimeout(scrollToBottom, 100)
            if (user.id != null) {
                deleteMessages(data.otherUser.id, user.id).then()
            }
        });
        //错误提示
        socket.on('error', (data) => {
            toast(data.message);
        });
        return () => {
            socket.off('chat_history');
            socket.off('error');
        };
    }, [socket]);

    useEffect(() => {
        readMessage(newsData.friend_id)
        //获取聊天历史 给自己发的聊天不会存放在数据库
        if (newsData.friend_email !== user.email) {
            socket.emit('get_chat_history', {otherUserEmail: newsData.friend_email});
        }
    }, []);

    const handleSend = () => {
        if (inputText.trim()) {
            const message: messageType = {
                id: user.id as number,
                name: user.name,
                avatar: user.avatar,
                time: new Date().getTime(),
                content: inputText,
                type: 0
            }
            setRecordList((prevState) => [...prevState, message]);
            if (newsData?.friend_email !== user.email) {
                const data: string = JSON.stringify(message)
                //发送消息
                socket.emit('private_message', {recipientEmail: newsData?.friend_email, message: data});
                AddChatHistory({recipientEmail: newsData?.friend_email, otherUserEmail: user.email, message: message})
            }
            setInputText("")
            setTimeout(scrollToBottom, 100)
        }
    };

    return <div className="PrivateChat">
        <div className="head centered">
            <Return2Icon onClick={() => navigate(-1)}></Return2Icon>
            <div>{newsData?.friend_name}</div>
            <div></div>
        </div>

        <ul className="record" ref={recordRef}>
            {recordList.map((item, index) =>
                <li key={item.time + item.content}>
                    {timeGaps[index] && <p>{formatDate(new Date(item.time))}</p>}
                    <div className={item.name == user.name ? "my-li" : ""}>
                        <div>
                            <img className="userHead" src={item.avatar} alt=""/>
                        </div>
                        <div className="record-content">{item.content}</div>
                    </div>
                </li>
            )}
        </ul>
        <div className="message-input">
            <InputIcon value={inputText} onKeyDown={(event) => {
                if (event.key === 'Enter') {
                    handleSend()
                }
            }} onChange={(e) => setInputText(e.target.value)}></InputIcon>
            <button className="z-button" onClick={handleSend}>发送</button>
        </div>
    </div>
}